package com.taptech.doufu.ui.fragment.story

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.taptech.doufu.R
import com.taptech.doufu.bean.ShareBeansInfo
import com.taptech.doufu.constant.Constant
import com.taptech.doufu.constant.ShareType
import com.taptech.doufu.constant.UmengEventName
import com.taptech.doufu.event.EventBusMyTag
import com.taptech.doufu.event.EventBusRefreshMyStory
import com.taptech.doufu.model.novel.bean.NovelDetailBean
import com.taptech.doufu.net.retrofit.RxBus
import com.taptech.doufu.ui.activity.BrowseActivity
import com.taptech.doufu.ui.activity.story.StoryCodeActivity
import com.taptech.doufu.ui.adapter.MyStoryAdapter
import com.taptech.doufu.ui.adapter.StoryAdapter
import com.taptech.doufu.ui.dialog.DoubleBtnTiptDialog
import com.taptech.doufu.ui.fragment.DiaobaoBaseFragment
import com.taptech.doufu.util.*
import com.taptech.doufu.weex.http.TFHttpUtil
import kotlinx.android.synthetic.main.fragment_my_story.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MyStoryFragment : DiaobaoBaseFragment(){


    val size = 20
    var page = 1
    lateinit var adapter: MyStoryAdapter
    lateinit var mRecyclerView: RecyclerView
    lateinit var mRefreshLayout: SmartRefreshLayout
    lateinit var layNone:View
//    lateinit var ivAdd:ImageView


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRefresh(event: EventBusRefreshMyStory) {
        if (event != null && !TextUtils.isEmpty(event.tag) && event.tag == EventBusRefreshMyStory.tag) {
            getData(true)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater?.inflate(R.layout.fragment_my_story, container, false)
        EventBus.getDefault().register(this)
        mRecyclerView = view.findViewById(R.id.mRecyclerView)
        mRefreshLayout = view.findViewById(R.id.mRefreshLayout)
        layNone = view.findViewById(R.id.layNone)
        adapter = MyStoryAdapter(context!!)
        adapter.onRightBtnClickListener = object :MyStoryAdapter.OnRightBtnClickListener{
            override fun onClick(item: NovelDetailBean, position: Int) {
                toastMoreDialog(item,position)
            }
        }
        mRecyclerView.layoutManager = LinearLayoutManager(context)
        mRecyclerView.adapter = adapter
        mRefreshLayout.setOnRefreshListener {
            getData(true)
        }
        mRefreshLayout.setOnLoadmoreListener {
            getData(false)
        }
        mRefreshLayout.autoRefresh()
        return view
    }

    fun getData(isRefresh: Boolean) {
        if (isRefresh){
            page = 1
        }
        val url = "http://api.doufu.la/topic/mine"
        val params = mutableMapOf<String,Any>()
        params["single_page"] = 1
        params["topic_type"] = 18
        params["size"] = size
        params["page"] = page
        TFHttpUtil.requestGet(url,params){ json, error ->
            try {
                val data = json.getJSONObject("data")
                page += 1
                val list = GsonUtil.jsonToList(data.getJSONArray("list").toJSONString(), Array<NovelDetailBean>::class.java)
                updateUI(isRefresh,list)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun toastMoreDialog(item: NovelDetailBean, position: Int) {
        val dialog = BottomSheetDialog(context!!)
        dialog.setContentView(R.layout.dialog_bottom_my_story_more)
        val tvCancel = dialog.findViewById<View>(R.id.tvCancel)
        val tvDelete = dialog.findViewById<View>(R.id.tvDelete)
        val tvShare = dialog.findViewById<View>(R.id.tvShare)
        if (item.audit_status == 0) {
            tvShare?.visibility = View.VISIBLE
        }else{
            tvShare?.visibility = View.GONE
        }
        tvDelete?.setOnClickListener {
            toastWarnDialog(item.id,position)
            dialog.dismiss()
        }
        tvShare?.setOnClickListener {
            shareSystemDialog(item)
//            shareMore(item)
            dialog.dismiss()
        }
        tvCancel?.setOnClickListener {
            dialog.dismiss()
        }
        dialog.show()
    }


    private fun shareSystemDialog(novelBean:NovelDetailBean) {
        val desc = "我正在 豆花 App 看《" + novelBean.title + "》小说，99%女生都在用的耽美言情BL同人小说阅读器，邀请你跟我一起看!!! " + novelBean.shareUrl
        ShareUtil.shareText(context!!, novelBean.title, desc)
    }

    private var shareDialog: BottomSheetDialog? = null


    private fun shareMore(novelBean:NovelDetailBean) {
        if (shareDialog == null) {
            shareDialog = ShareUtils.getBottomDialog(context,false,object : ShareUtils.OnClickListener{
                override fun onClickHelp() {
                    BrowseActivity.startActivity(context,"https://api.doufu.la/journal/detail?id=745")
                }

                override fun onClickItem(social_type: Int) {
                    val map = HashMap<String, String>()
                    map["type"] = "$social_type"
                    TMAnalysis.event(context, UmengEventName.NOVEL_DETAIL_MORE_SHARE_ACTION, map)
                    when (social_type) {
                        ShareType.CopyLink -> ShareUtils.copyLike(context,getShareBean(novelBean).shareUrl)
                        ShareType.Weibo ->{
                            val shareBean = getShareBean(novelBean)
                            shareBean.shartText = getWeiboShareText(novelBean)
                            shareBean.social_type = social_type
                            ShareUtils.thirdPartyShare(context,shareBean)
                        }
                        else -> {
                            val shareBean = getShareBean(novelBean)
                            shareBean.social_type = social_type
                            ShareUtils.thirdPartyShare(context,shareBean)
                        }
                    }
                }
            })
            shareDialog?.findViewById<View>(R.id.layMakePoster)?.visibility = View.INVISIBLE
        }
        shareDialog?.show()
    }

    fun getShareBean(novelBean:NovelDetailBean): ShareBeansInfo {
        val shareBean = ShareBeansInfo()
        shareBean.id = "${novelBean.id}"
        shareBean.dataType = 1
        var shareText = StringUtil.filterAllSpace(novelBean.description)
        if (shareText != null && shareText.length > 50) {
            shareBean.shartText = shareText.substring(0,50)
        }else{
            shareBean.shartText = shareText
        }
        shareBean.imagUrl = ""
        shareBean.title = "${novelBean.title}"
        shareBean.shareUrl = novelBean.shareUrl
        shareBean.object_type = "${novelBean.object_type}"
        return shareBean
    }


    fun getWeiboShareText(novelBean:NovelDetailBean) :String{
        var text = "介绍豆花作者：${novelBean.user.name}的文章《${novelBean.title}》${novelBean.shareUrl}"
        novelBean.tags.forEach {
            text+="#${it.name}"
        }
        return text
    }



    fun toastWarnDialog(id:Int,position: Int) {
        val dialog = DoubleBtnTiptDialog(context!!,R.style.updateDialog,
                "确定要删除该作品吗？","确定", DoubleBtnTiptDialog.CallBack {
                deleteStory(id, position)
        })
        dialog.show()
    }

    fun deleteStory(id:Int,position: Int) {
        val url = "http://api.doufu.la/index.php/post/removeTopic"
        val params = mutableMapOf<String,Any>()
        params["id"]=id
        TFHttpUtil.requestPost(url,params){json, error ->
            try {
                val status = json.getIntValue("status")
                if (status == 0) {
                    Toast.makeText(context,"删除成功",Toast.LENGTH_LONG).show()
                    adapter.dataList.removeAt(position)
                    adapter.notifyDataSetChanged()
                    if (adapter.dataList.size > 0) {
                        layNone.visibility = View.GONE
                    }else{
                        layNone.visibility = View.VISIBLE
                    }
                }else{
                    Toast.makeText(context,"删除失败",Toast.LENGTH_LONG).show()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun updateUI(isRefresh: Boolean,list: MutableList<NovelDetailBean>) {
        val formatList = ArrayList(list)
        if (formatList.size < size) {
            mRefreshLayout.isEnableLoadmore = false
        }
        if (isRefresh) {
            adapter.setData(formatList)
            mRefreshLayout.finishRefresh()
        }else{
            adapter.addData(formatList)
            mRefreshLayout.finishLoadmore()
        }
        if (adapter.dataList.size > 0) {
            layNone.visibility = View.GONE
        }else{
            layNone.visibility = View.VISIBLE
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    companion object{
        fun newInstance(): MyStoryFragment {
            return MyStoryFragment()
        }
    }

}